package org.ofbiz.wvtools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.w3c.dom.Document;

public class BackupCompanyDataServices {

	public static final String module = BackupCompanyDataServices.class.getName();
	
	public static final String OFBIZ_HOME = System.getProperty("ofbiz.home");
	public static final String filePath  = "/hot-deploy/sys/webapp/sys/images/company/";
	
	public static void main(String[] args) throws Exception {
		
		String path ="D:\\xmlbackup";
		File file = new File(path);
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for(File fileIndex:files){
				System.out.println(fileIndex.getName());
			}
			
		}

	}
	// 列出所有备份公司数据
	public static  Map<String,Object> listCompanyBackup(DispatchContext ctx, Map<String, ? extends Object> context){
		Map<String,Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String haveFilePath = (String) context.get("haveFilePath");
		List nfsList=new ArrayList();
		
		//String filePath  = "/hot-deploy/sys/webapp/sys/images/company/";
		String path= OFBIZ_HOME+ filePath;
		File file = new File(path);
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for(File fileIndex:files){
				System.out.println(fileIndex.getName());
				if("Y".equals(haveFilePath)) {
					nfsList.add(filePath+fileIndex.getName());
				}else {
					nfsList.add(fileIndex.getName());
				}
				
			}
			
		}
		
		 result.put("nfsList", nfsList);
    	 result.put("totalCount", nfsList.size());
		Debug.log("listCompanyBackup   === end");
		return result;
	}

	
	// 备份公司数据，并删除数据库
	public static  Map<String,Object> backupCompany(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("backupCompany   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String companyId = (String) context.get("companyId");
		String fileName = (String) context.get("fileName");

		fileName= OFBIZ_HOME+ filePath+ fileName;
		
		
		List<GenericValue> nfsList=new ArrayList();
        try {
        	
        	String[] companyArray =companyId.split(",");
        	for(int i=0;i<companyArray.length;i++) {
        		
        		String singleCompanyId =companyArray[i];
    			//System.out.println(companyArray[i]);
    			nfsList.addAll(getSingleCompanyData(delegator, singleCompanyId));
    			removeSingleCompanyData( delegator, singleCompanyId);
    		}

        	
        	
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
        try {
        	 result.put("nfsList", nfsList);
        	 result.put("totalCount", nfsList.size());
        	 Document mainDoc = GenericValue.makeXmlDocument(nfsList);
        	 UtilXml.writeXmlDocument(fileName, mainDoc);
		} catch (IOException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
        Debug.log("backupCompany   === end");
		return result;
	}
	
	// 备份公司数据
	public static  Map<String,Object> exportBackupCompany(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("exportBackupCompany   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String companyId = (String) context.get("companyId");
		String fileName = (String) context.get("fileName");
		fileName= OFBIZ_HOME+ filePath+ fileName;
		
		
		List<GenericValue> nfsList=new ArrayList();
        try {
        	
        	String[] companyArray =companyId.split(",");
        	for(int i=0;i<companyArray.length;i++) {
        		
        		String singleCompanyId =companyArray[i];
    			nfsList.addAll(getSingleCompanyData(delegator, singleCompanyId));
    		}
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
        try {
        	 result.put("nfsList", nfsList);
        	 result.put("totalCount", nfsList.size());
        	 Document mainDoc = GenericValue.makeXmlDocument(nfsList);
        	 UtilXml.writeXmlDocument(fileName, mainDoc);
		} catch (IOException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
        Debug.log("exportBackupCompany   === end");
		return result;
	}
	
	
	
	// 删除数据库中公司数据
	public static  Map<String,Object> deleteBackupCompany(DispatchContext ctx, Map<String, ? extends Object> context){
		Debug.log("deleteBackupCompany   === start");
		Map<String,Object> result = ServiceUtil.returnSuccess();
		Delegator delegator = ctx.getDelegator();
		String companyId = (String) context.get("companyId");
//		String fileName = (String) context.get("fileName");
//		
//		fileName= OFBIZ_HOME+ filePath+ fileName;
		
		
        try {
        	
        	String[] companyArray =companyId.split(",");
        	for(int i=0;i<companyArray.length;i++) {
        		
        		String singleCompanyId =companyArray[i];
    			
    			removeSingleCompanyData( delegator, singleCompanyId);
    		}

        	
		} catch (GenericEntityException e) {
			Debug.logError(e.getMessage(), module);
			return ServiceUtil.returnError(e.getMessage());
		}
        
        Debug.log("deleteBackupCompany   === end");
		return result;
	}
	
	
	private static List<GenericValue> getSingleCompanyData(Delegator delegator,String companyId) throws GenericEntityException {
		List<GenericValue> nfsList=new ArrayList();
    	
//    	公司组织结构
		GenericValue party = delegator.findOne("Party", UtilMisc.toMap("partyId", companyId), false);
    	nfsList.add(removeField(party));
    	List<GenericValue> partyRoleList =delegator.findByAnd("PartyRole", UtilMisc.toMap("partyId", companyId), null, false);
    	nfsList.addAll(removeField(partyRoleList));
    	GenericValue partyGroup = EntityQuery.use(delegator).from("PartyGroup").where("partyId", companyId).queryOne();
    	nfsList.add(removeField(partyGroup));
    	
    	List<GenericValue> coAccountList =delegator.findByAnd("CoAccount", UtilMisc.toMap("partyId", companyId), null, false);
    	nfsList.addAll(removeField(coAccountList));
//      员工列表    	
    	
    	List<GenericValue> personList =delegator.findByAnd("Person", UtilMisc.toMap("companyId", companyId), null, false);
    	
    	for(GenericValue person:personList) {
    		String partyId=person.getString("partyId");
    		GenericValue person_party = delegator.findOne("Party", UtilMisc.toMap("partyId", partyId), false);
        	nfsList.add(removeField(person_party));
        	List<GenericValue> person_partyRoleList =delegator.findByAnd("PartyRole", UtilMisc.toMap("partyId", partyId), null, false);
        	nfsList.addAll(removeField(person_partyRoleList));
        	//GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), false);
        	nfsList.add(removeField(person));
        	
        	List<GenericValue> userLoginList =delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId), null, false);
        	nfsList.addAll(removeField(userLoginList));
        	for(GenericValue item:userLoginList) {
        		String userLoginId=item.getString("userLoginId");
        		List<GenericValue> userLoginSecurityGroupList =delegator.findByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId), null, false);
            	nfsList.addAll(removeField(userLoginSecurityGroupList));
        		
        	}
    		
    	}
    	
   // 店铺
    	List<GenericValue> letStoreList =delegator.findByAnd("LetStore", UtilMisc.toMap("companyId", companyId), null, false);
    	
    	nfsList.addAll(removeField(letStoreList));
    	for(GenericValue item:letStoreList) {
    		String productStoreId=item.getString("productStoreId");
    		nfsList.addAll(getLetStoreData(delegator,productStoreId));
    	}
    	
        List<GenericValue> zebCmsArticleList =delegator.findByAnd("ZebCmsArticle", UtilMisc.toMap("companyId", companyId), null, false);
    	
    	nfsList.addAll(removeField(zebCmsArticleList));
    	
    	
        List<GenericValue> letProductList =delegator.findByAnd("LetProduct", UtilMisc.toMap("ownerPartyId", companyId), null, false);
    	
    	nfsList.addAll(removeField(letProductList));
    	
    	return nfsList;
	}
	
	   // 店铺
	private static List<GenericValue> getLetStoreData(Delegator delegator,String productStoreId) throws GenericEntityException{
		
		List<GenericValue> nfsList=new ArrayList();
		
		
		
		List<GenericValue> zebStoreCategoryList =delegator.findByAnd("ZebStoreCategory", UtilMisc.toMap("productStoreId", productStoreId), null, false);
    	nfsList.addAll(removeField(zebStoreCategoryList));
    	
    	List<GenericValue> letStoreToProductList =delegator.findByAnd("LetStoreToProduct", UtilMisc.toMap("productStoreId", productStoreId), null, false);
    	nfsList.addAll(removeField(letStoreToProductList));
    	//TODO 产品


    	List<GenericValue> zebStoreFirstCmsList =delegator.findByAnd("ZebStoreFirstCms", UtilMisc.toMap("productStoreId", productStoreId), null, false);
    	nfsList.addAll(removeField(zebStoreFirstCmsList));
    	
		 
		//客户列表 
		List<GenericValue> coRelationshipList =delegator.findByAnd("CoRelationship", UtilMisc.toMap( "partyRelationshipTypeId","STORE_CUSTOMER","partyIdTo", productStoreId), null, false);
    	for(GenericValue coRelationship:coRelationshipList) {
    		String partyId=coRelationship.getString("partyIdFrom");
    		GenericValue party = delegator.findOne("Party", UtilMisc.toMap("partyId", partyId), false);
        	nfsList.add(removeField(party));
        	List<GenericValue> partyRoleList =delegator.findByAnd("PartyRole", UtilMisc.toMap("partyId", partyId), null, false);
        	nfsList.addAll(removeField(partyRoleList));
        	GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), false);
        	nfsList.add(removeField(person));
        	
        	List<GenericValue> userLoginList =delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId), null, false);
        	nfsList.addAll(removeField(userLoginList));
//        	for(GenericValue item:userLoginList) {
//        		String userLoginId=item.getString("userLoginId");
//        		List<GenericValue> userLoginSecurityGroupList =delegator.findByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId), null, false);
//            	nfsList.addAll(removeField(userLoginSecurityGroupList));
//        		
//        	}
        	nfsList.add(removeField(coRelationship));
    	}
		
		    return nfsList;
	}
	
	private static void removeSingleCompanyData(Delegator delegator,String companyId) throws GenericEntityException{
    	
		
		
    	delegator.removeByAnd("Party", UtilMisc.toMap("partyId", companyId));
    	delegator.removeByAnd("PartyRole", UtilMisc.toMap("partyId", companyId));
		delegator.removeByAnd("PartyGroup", UtilMisc.toMap("partyId", companyId));
    	delegator.removeByAnd("CoAccount", UtilMisc.toMap("partyId", companyId));
	
    	List<GenericValue> personList =delegator.findByAnd("Person", UtilMisc.toMap("companyId", companyId), null, false);
    	
    	for(GenericValue person:personList) {
    		String partyId=person.getString("partyId");
        	List<GenericValue> userLoginList =delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId), null, false);
        	
        	//删除UserLogin 前置
        	for(GenericValue item:userLoginList) {
        		
        		String userLoginId=item.getString("userLoginId");
        		Debug.log("userLoginId = "+userLoginId);   
        		
        		List<GenericValue> visitorList =delegator.findByAnd("Visitor", UtilMisc.toMap("userLoginId", userLoginId), null, false);
        		for(GenericValue visitorItem:visitorList) {
        			String visitorId =visitorItem.getString("visitorId");
        			List<GenericValue> visitList =delegator.findByAnd("Visit", UtilMisc.toMap("visitorId", visitorId), null, false);
            		for(GenericValue visitItem:visitList) {
            			String visitId =visitItem.getString("visitId");   
            			delegator.removeByAnd("ServerHit", UtilMisc.toMap("visitId", visitId));
            		}
        			
        			
        			
        			
        			
        			Debug.log("visitorId = "+ visitorId);                          
        			delegator.removeByAnd("Visit", UtilMisc.toMap("visitorId", visitorId));
        		}
        		delegator.removeByAnd("Visitor", UtilMisc.toMap("userLoginId", userLoginId));
        		
        		delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId));
        		delegator.removeByAnd("UserLoginToken", UtilMisc.toMap("userLoginId", userLoginId));
        		
        	}
        	
        	delegator.removeByAnd("UserLogin", UtilMisc.toMap("partyId", partyId));
        	delegator.removeByAnd("Person", UtilMisc.toMap("partyId", partyId));
    		delegator.removeByAnd("PartyRole", UtilMisc.toMap("partyId", partyId));
    		delegator.removeByAnd("Party", UtilMisc.toMap("partyId", partyId));
    		
    	}
    	
    	List<GenericValue> letStoreList =delegator.findByAnd("LetStore", UtilMisc.toMap("companyId", companyId), null, false);
    	for(GenericValue item:letStoreList) {
    		String productStoreId=item.getString("productStoreId");
    		

    		
    		delegator.removeByAnd("ZebStoreCategory", UtilMisc.toMap("productStoreId", productStoreId) );
        	delegator.removeByAnd("LetStoreToProduct", UtilMisc.toMap("productStoreId", productStoreId) );
        	//TODO 产品
        	delegator.removeByAnd("ZebStoreFirstCms", UtilMisc.toMap("productStoreId", productStoreId) );
        	
    		
    		
    		List<GenericValue> coRelationshipList =delegator.findByAnd("CoRelationship", UtilMisc.toMap( "partyRelationshipTypeId","STORE_CUSTOMER","partyIdTo", productStoreId), null, false);
	    	for(GenericValue coRelationship:coRelationshipList) {
	    		String partyId=coRelationship.getString("partyIdFrom");
	    		
//	    		delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId));
	        	List<GenericValue> userLoginList =delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId), null, false);
	        	
	        	//删除UserLogin 前置
	        	for(GenericValue userLogin:userLoginList) {
	        		
	        		String userLoginId=userLogin.getString("userLoginId");
	        		Debug.log("userLoginId = "+userLoginId);   
	        		
	        		List<GenericValue> visitorList =delegator.findByAnd("Visitor", UtilMisc.toMap("userLoginId", userLoginId), null, false);
	        		for(GenericValue visitorItem:visitorList) {
	        			String visitorId =visitorItem.getString("visitorId");
	        			List<GenericValue> visitList =delegator.findByAnd("Visit", UtilMisc.toMap("visitorId", visitorId), null, false);
	            		for(GenericValue visitItem:visitList) {
	            			String visitId =visitItem.getString("visitId");   
	            			delegator.removeByAnd("ServerHit", UtilMisc.toMap("visitId", visitId));
	            		}
	        			
	        			Debug.log("visitorId = "+ visitorId);                          
	        			delegator.removeByAnd("Visit", UtilMisc.toMap("visitorId", visitorId));
	        		}
	        		delegator.removeByAnd("Visitor", UtilMisc.toMap("userLoginId", userLoginId));
	        		
	        		delegator.removeByAnd("UserLoginSecurityGroup", UtilMisc.toMap("userLoginId", userLoginId));
	        		delegator.removeByAnd("UserLoginToken", UtilMisc.toMap("userLoginId", userLoginId));
	        		
	        	}
	    		delegator.removeByAnd("UserLogin", UtilMisc.toMap("partyId", partyId));
	        	delegator.removeByAnd("Person", UtilMisc.toMap("partyId", partyId));
	    		delegator.removeByAnd("PartyRole", UtilMisc.toMap("partyId", partyId));
	    		delegator.removeByAnd("Party", UtilMisc.toMap("partyId", partyId));
	    	}
	    	delegator.removeByAnd("CoRelationship", UtilMisc.toMap("partyRelationshipTypeId","STORE_CUSTOMER","partyIdTo", productStoreId));
    	
    	
    	
    	}
    	delegator.removeByAnd("LetProduct", UtilMisc.toMap("ownerPartyId", companyId));
    	delegator.removeByAnd("LetStore", UtilMisc.toMap("companyId", companyId));
    	delegator.removeByAnd("ZebCmsArticle", UtilMisc.toMap("companyId", companyId));
    
    			
	}
	
	private static GenericValue removeField(GenericValue oldItem){
		
		GenericValue entity =GenericValue.create(oldItem);
		entity.remove("createdStamp");
		entity.remove("createdTxStamp");
		entity.remove("lastUpdatedStamp");
		entity.remove("lastUpdatedTxStamp");
		entity.remove("removed");
    	return entity;
    	
    	
	}
	
	private static List<GenericValue> removeField(List<GenericValue> oldList){
		List<GenericValue> list=new ArrayList();
		for(GenericValue oldItem:oldList) {
			
			GenericValue entity =GenericValue.create(oldItem);
			entity.remove("createdStamp");
			entity.remove("createdTxStamp");
			entity.remove("lastUpdatedStamp");
			entity.remove("lastUpdatedTxStamp");
			entity.remove("removed");
			list.add(entity);
		}
		
    	
    	return list;
    	
    	
	}
	
	
	

}
